import { nextTick } from "vue";
import { widget, store, mars3d, Cesium } from "@/utils/global";
import { saveDrawData, updateDrawData } from "@/api/draw";
import { newTreeNode } from "@/utils/coverage/coverage";
import renderer from "@/utils/draw/renderer";
import { addUserStyle } from "@/api/tool";
import { ElMessage, ElMessageBox } from "element-plus";
import { calcVolume } from "@/utils/draw/saveEditorDrawData";
// import { turf } from "@turf/turf";
import * as turf from "@turf/turf";
/**
 * @function monitor 监听图层绘制及绘制过程和结束
 * @param graphicLayer 图层对象
 * @author scw 2024-1-31 15:02:18
 */
export function monitor(graphicLayer: any) {
    graphicLayer
        .on(mars3d.EventType.drawCreated, (e: any) => {
            /**
             * 绘制完成
             */
            let graphic = e.graphic;
            console.log(widget.drawItemData, "321");
            // nearestPoint(graphicLayer, graphic);
            // 处理图标
            graphic.setOptions({
                icon: widget.drawItemData.pic,
            });
            // console.log(widget.drawItemData.pic);
            // return;
            // 处理要上传的数据
            let postData = JSON.parse(JSON.stringify(graphic.toJSON()));
            postData.style = JSON.stringify(postData.style);
            if (postData.position) {
                postData.positions = JSON.stringify(postData.position);
                postData.position = JSON.stringify(postData.position);
            } else {
                postData.positions = JSON.stringify(postData.positions);
            }
            postData.isShow = 1;
            postData.isLocked = 0;
            postData.isCustom = store.isCustom;
            // console.log(graphic, postData);
            // 保存数据
            saveDrawData(postData).then((res: any) => {
                store.isCustom = 0;
                // 删除当前绘制的数据
                graphicLayer.removeGraphic(graphic);
                // 重新渲染数据,避免操作数据时获取失败
                console.log(res.data);
                renderer([res.data]);
                nextTick(() => {
                    res.data.icon = `${import.meta.env.VITE_BASE_XYZ}${res.data.icon}`;
                    let node = newTreeNode(res.data);
                    store.tree.append(node, node.pid);
                    nextTick(() => {
                        store.tree.setChecked(node.id, true, true);
                        store.tree.setCurrentKey(node.id);

                        // if (res.data.type == "polyline") {
                        //     nearestPoint(graphicLayer, res.data);
                        // }
                    });
                });
                // 保存用户自定义样式
                if (widget.addStyle) {
                    let newDrawData = JSON.parse(JSON.stringify(widget.drawItemData));
                    delete newDrawData.id;
                    newDrawData.drawId = res.data.id;
                    addUserStyle(newDrawData).then((draws: any) => {
                        // 添加数据到列表
                        console.log(draws.data);
                        widget.customStyleItem.push(draws.data);
                        widget.addStyle = false;
                    });
                }
            });
        })
        .on(mars3d.EventType.drawStart, (e: any) => {
            /**
             * 绘制开始
             */
            let graphic = e.graphic;
        })
        .on(mars3d.EventType.drawAddPoint, (e: any) => {
            /**
             * 绘制过程中添加了点
             */
            // widget.isEditorStyles = true;
            let graphic = e.graphic;
            // console.log(graphic);
            // return;
        })
        .on(mars3d.EventType.drawRemovePoint, (e: any) => {
            /**
             * 绘制过程中删除了点
             */
            // widget.isEditorStyles = true;
        })
        .on(mars3d.EventType.editMovePoint, (e: any) => {
            /**
             * 编辑修改了点的位置
             */
            console.log("编辑修改了点的位置");
            widget.isEditorStyles = true;
            let graphic = e.graphic;
            updateEditorTip(graphic);

            // widget.editFormKey = new Date().getTime();
        })
        .on(mars3d.EventType.drawMouseMove, (e: any) => {
            /**
             * 正在移动鼠标中，绘制过程中鼠标移动了点 标绘事件
             */
        })
        .on(mars3d.EventType.editRemovePoint, (e: any) => {
            /**
             * 编辑删除点事件
             */
            console.log("编辑删除点事件");
            widget.isEditorStyles = true;
            let graphic = e.graphic;
            updateEditorTip(graphic);
        })
        .on(mars3d.EventType.editStart, (e: any) => {
            /**
             * 编辑开始事件
             */
            let graphic = e.graphic;
        })
        .on(mars3d.EventType.rightClick, (e: any) => {
            /**
             * 右键事件
             */

            // console.log(e);
            e.stopPropagation();
            let graphic = e.graphic;
            if (graphic.options.attr.from == "farmboss") {
                return false;
            }
            // 右键删除点
            if (!store.tree.getNode(graphic.id) && graphic.type == "pointP") {
                e.propagatedFrom._contextmenuConfig.content[0].callback(e);
                updateEditorTip(graphic.parent);
                // 数据不存在
                return false;
            }
            try {
                let node = store.tree.getNode(graphic.id).data;
                if (node.isLocked == 1) {
                    // 标绘上锁
                    ElMessage.warning("该标绘已被锁定,无法编辑!");
                } else {
                    // 判断数据是否正在编辑状态
                    if (!graphic.isEditing) {
                        store.rightClickData = graphic;
                        // 右键菜单参数赋值
                        widget.contextMenu.X = e.position.x;
                        widget.contextMenu.Y = e.position.y;
                        widget.contextMenu.type = "mapDraw";
                        widget.contextMenu.show = true;
                    }
                }
            } catch (error) {
                store.rightClickData = graphic;
                // 右键菜单参数赋值
                widget.contextMenu.X = e.position.x;
                widget.contextMenu.Y = e.position.y;
                widget.contextMenu.type = "sign";
                widget.contextMenu.show = true;
            }
        })
        .on(mars3d.EventType.click, (e: any) => {
            /**
             * 单击事件
             */
            let graphic = e.graphic;
            // 单击标绘,选中树菜单
            store.tree.setCurrentKey(graphic.id, true);
        })
        .on(mars3d.EventType.dblClick, (e: any) => {
            /**
             * 双击事件
             */
        });
}
/**
 * 添加数据到图层
 */
const toTreeDatas = (treeData: any, data: any) => {
    treeData.forEach((v: any, i: any) => {
        if (v.id == data.pid) {
            v.children.unshift(data);
        } else {
            if (v.children) {
                toTreeDatas(v.children, data);
            }
        }
    });
};
/**
 * 编辑点时,更新显示的文案
 */
const updateEditorTip = (graphic: any) => {
    let style = graphic.style;
    // console.log("label" in style);
    // return;
    if ("label" in style && (style.label.isLength || style.label.isArea || style.label.isVolume)) {
        if (style.label.isLength) {
            // 长度
            graphic.setStyle({
                label: {
                    text: graphic.distance.toFixed(2) + " m",
                },
            });
        } else if (style.label.isArea) {
            // 面积
            if (graphic.options.plottingType == "plane") {
                graphic.setStyle({
                    label: {
                        text: (style.dimensions_y * style.dimensions_x).toFixed(2) + " ㎡",
                    },
                });
            } else {
                if (graphic.options.plottingType == "polygon") {
                    // 多边形
                    console.log(style.label);
                    // return;
                    let showText = "";
                    if (style.label.unit == "1") {
                        showText = graphic.area.toFixed(2) + " ㎡";
                    }
                    if (style.label.unit == "2") {
                        showText = (graphic.area / 666.67).toFixed(2) + " 亩";
                    }
                    if (style.label.unit == "3") {
                        showText = (graphic.area / 10000).toFixed(2) + "公顷";
                    }
                    graphic.setStyle({
                        label: {
                            text: showText,
                        },
                    });
                } else {
                    graphic.setStyle({
                        label: {
                            text: graphic.area.toFixed(2) + " m²",
                        },
                    });
                }
            }
        } else if (style.label.isVolume) {
            // 体积
            graphic.setStyle({
                label: {
                    text: calcVolume(graphic).toFixed(2) + " m³",
                },
            });
        }
    }

    widget.editFormKey = new Date().getTime();
};

/**
 * 最近点计算
 */
const nearestPoint = (graphicLayer: any, data: any) => {
    // 获取所有线段并且排除当前线段
    const lineLayer = graphicLayer.getGraphics().filter((item: any) => {
        return item.id != data.id && item.type == "polyline";
    });
    if (lineLayer.length < 1) {
        return;
    }
    const firstDistanceList: any = [];
    const lastDistanceList: any = [];
    // 遍历所有线段并拿到小于0.1米的最近点
    lineLayer.forEach((v: any, i: any) => {
        const line = v.toGeoJSON();
        // ****************************************************处理第一个坐标点****************************************************
        // 当前数据的第一个坐标点
        const firstPoint = data.positions[0];
        // 计算第一个坐标点最近点,,,,单位千米
        const firstSnapped = turf.nearestPointOnLine(line, firstPoint, { units: "miles" });
        // 计算第一个坐标点的距离并转换为米
        const firstDistance = turf.distance(firstSnapped.geometry.coordinates, firstPoint, { units: "miles" }) * 1000;
        // 把距离和位置存入数组
        if (firstDistance <= 0.1) {
            firstDistanceList.push({
                distance: firstDistance,
                position: firstSnapped.geometry.coordinates,
            });
        }

        // ****************************************************处理最后一个坐标点****************************************************
        // 当前数据的最后一个坐标点
        const lastPoint = data.positions[data.positions.length - 1];
        // 计算最后一个坐标点最近点,,,,单位千米
        const lastSnapped = turf.nearestPointOnLine(line, lastPoint, { units: "miles" });
        // 计算最后一个坐标点的距离并转换为米
        const lastDistance = turf.distance(firstSnapped.geometry.coordinates, lastPoint, { units: "miles" }) * 1000;
        // 把距离和位置存入数组
        if (lastDistance <= 0.1) {
            lastDistanceList.push({
                distance: lastDistance,
                position: lastSnapped.geometry.coordinates,
            });
        }

        // let postData = JSON.parse(JSON.stringify(graphic.toJSON()));
        // postData.style = JSON.stringify(postData.style);
        // if (postData.position) {
        //     postData.positions = JSON.stringify(postData.position);
        //     postData.position = JSON.stringify(postData.position);
        // } else {
        //     postData.positions = JSON.stringify(postData.positions);
        // }
        // postData.isShow = graphic.show ? "1" : "0";
        // updateDrawData(postData);
    });
    nextTick(() => {
        // 两组数据按照从小到大排序
        const firstList = firstDistanceList.sort((a: any, b: any) => {
            return a.distance - b.distance;
        });
        const lastList = lastDistanceList.sort((a: any, b: any) => {
            return a.distance - b.distance;
        });
        // 判断最小距离是否小于0.1米
        if (firstList.length > 0) {
            data.positions[0] = firstList[0].position;
        }
        if (lastList.length > 0) {
            data.positions[data.positions.length - 1] = lastList[0].position;
        }

        updateGraphicPosition(data, graphicLayer);
    });
};
const updateGraphicPosition = (data: any, graphicLayer: any) => {
    const graphic = graphicLayer.getGraphicById(data.id);
    graphic.setCallbackPositions(data.positions);
    let postData = JSON.parse(JSON.stringify(graphic.toJSON()));
    postData.style = JSON.stringify(postData.style);
    if (postData.position) {
        postData.positions = JSON.stringify(postData.position);
        postData.position = JSON.stringify(postData.position);
    } else {
        postData.positions = JSON.stringify(postData.positions);
    }
    postData.isShow = graphic.show ? "1" : "0";
    updateDrawData(postData);
};
